package com.winit.openapi.tp.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.utils.Dates;
import com.winit.mqx.vo.tp.KuaiDi100TrackingMessage;
import com.winit.mqx.vo.tp.TrackingMessage;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.EnumConstant;
import com.winit.openapi.mqx.KuaiDi100TrackingMqxSender;
import com.winit.openapi.mqx.vo.SyncResult;
import com.winit.openapi.tp.model.NoticeRequest;
import com.winit.openapi.tp.model.NoticeResponse;
import com.winit.openapi.tp.model.Result;
import com.winit.openapi.tp.model.ResultItem;

/**
 * 快递100推送
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * zq 	1.0  		2015年10月28日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class KuaiDi100CallbackController {

    private static final Logger        logger = LoggerFactory.getLogger(KuaiDi100CallbackController.class);

    @Resource
    private KuaiDi100TrackingMqxSender kuaiDi100TrackingMqxSender;

    /**
     * 快递100推送处理controller
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/KuaiDi100Callback")
    @ResponseBody
    public NoticeResponse callback(HttpServletRequest request) {
        String param = request.getParameter("param");
        if (StringUtils.isBlank(param)) {
            logger.info("KuaiDi100CallbackController.callback参数为空 ");
            return returnMsg(false, "500", "param参数为空");
        }

        String orderNo = request.getParameter("no");
        if (StringUtils.isBlank(orderNo)) {
            logger.info("KuaiDi100CallbackController.callback:orderNo参数为空 ");
            return returnMsg(false, "500", "No参数为空");
        }
        // 推送返回实体
        NoticeResponse resp = new NoticeResponse();
        try {
            // 解析json转化实体
            JSONObject obj = JSONObject.parseObject(param);
            NoticeRequest nReq = conversionEntity(obj);
            Result result = nReq.getLastResult();

            KuaiDi100TrackingMessage message = new KuaiDi100TrackingMessage();
            message.setOrderNo(orderNo);
            message.setTrackingNo(result.getNu());// 快递单号
            message.setState(result.getState());// 当前快递单状态
            message.setMessage(nReq.getMessage());// 监控状态相关消息
            message.setStatus(nReq.getStatus());// 监控状态
            message.setSoure(ApiConstant.EXPRESSSOURCE);//快递来源
            message.setLastEvent(nReq.getStatus().equals(EnumConstant.MonitorStatus.SHUTDOWN.getVal())?"Y":"N");//是否最后轨迹
            // 组装轨迹信息
            List<TrackingMessage> list = new ArrayList<TrackingMessage>();
            if (null != result.getData() && result.getData().size() > 0) {
                for (ResultItem item : result.getData()) {
                    TrackingMessage msg = new TrackingMessage();
                    msg.setAreaName(item.getAreaName());
                    msg.setTrackingDesc(item.getContext());
                    msg.setTrackingDate(Dates.parseDate(item.getFtime(), "yyyy-MM-dd hh:mm:ss"));
                    msg.setStatus(item.getStatus());
                    list.add(msg);
                }
                message.setTrackingMessage(list);
            }
            // 推送到MQ
            SyncResult syncResult=kuaiDi100TrackingMqxSender.exec(message);
            if(syncResult.getCode().equals(SyncResult.SYNC_RESULT_CODE_SUCCESS)){
                resp = returnMsg(true, "200", "成功");
            }else {
                resp = returnMsg(true, "500", syncResult.getMsg());
            }
        } catch (Exception e) {
            logger.error("KuaiDi100CallbackController.callback 异常:" + e);
            resp = returnMsg(false, "500", e.getLocalizedMessage());
        }
        return resp;
    }

    /**
     * 回调消息
     * 
     * @param result
     * @param code
     * @param msg
     * @return NoticeResponse
     */
    private NoticeResponse returnMsg(boolean result, String code, String msg) {
        NoticeResponse resp = new NoticeResponse();
        resp.setResult(result);
        resp.setReturnCode(code);
        resp.setMessage(msg);
        return resp;
    }

    /**
     * 转换成实体对象
     * 
     * @param json
     * @return NoticeRequest
     */
    private NoticeRequest conversionEntity(JSONObject json) {
        NoticeRequest request = new NoticeRequest();
        if (json.containsKey("status")) {
            request.setStatus(json.getString("status").trim());
        }
        if (json.containsKey("billstatus")) {
            request.setBillstatus(json.getString("billstatus").trim());
        }
        if (json.containsKey("message")) {
            request.setMessage(json.getString("message").trim());
        }
        if (json.containsKey("lastResult")) {
            JSONObject lastResult = json.getJSONObject("lastResult");
            Result result = new Result();
            if (lastResult.containsKey("message")) {
                result.setMessage(lastResult.getString("message").trim());
            }
            if (lastResult.containsKey("state")) {
                result.setState(lastResult.getString("state").trim());
            }
            if (lastResult.containsKey("status")) {
                result.setStatus(lastResult.getString("status").trim());
            }
            if (lastResult.containsKey("condition")) {
                result.setCondition(lastResult.getString("condition").trim());
            }
            if (lastResult.containsKey("ischeck")) {
                result.setIscheck(lastResult.getString("ischeck").trim());
            }
            if (lastResult.containsKey("com")) {
                result.setCom(lastResult.getString("com").trim());
            }
            if (lastResult.containsKey("nu")) {
                result.setNu(lastResult.getString("nu").trim());
            }
            if (lastResult.containsKey("data")) {
                ArrayList<ResultItem> arrayList = new ArrayList<ResultItem>();
                JSONArray data = JSONArray.parseArray(lastResult.get("data").toString());
                for (Object object : data) {
                    JSONObject jsonObject = (JSONObject) object;
                    ResultItem resultItem = new ResultItem();
                    if (jsonObject.containsKey("context")) {
                        resultItem.setContext(jsonObject.getString("context").trim());
                    }
                    if (jsonObject.containsKey("time")) {
                        resultItem.setTime(jsonObject.getString("time").trim());
                    }
                    if (jsonObject.containsKey("ftime")) {
                        resultItem.setFtime(jsonObject.getString("ftime").trim());
                    }
                    if (jsonObject.containsKey("status")) {
                        resultItem.setStatus(jsonObject.getString("status").trim());
                    }
                    if (jsonObject.containsKey("areaName")) {
                        resultItem.setAreaName(jsonObject.getString("areaName").trim());
                    }
                    arrayList.add(resultItem);
                }
                result.setData(arrayList);
            }
            request.setLastResult(result);
        }

        return request;
    }
}
